package cn.com.ejiakanghu.job;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.system.SystemConfig;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.util.OrderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 检测订单状态
 */
@Component
public class OrderJob {
    private final Log logger = LogFactory.getLog(OrderJob.class);

    @Autowired
    private LitemallOrderGoodsService orderGoodsService;
    @Autowired
    private LitemallOrderService orderService;
    @Autowired
    private LitemallGoodsProductService productService;
    @Autowired
    private LitemallGrouponService grouponService;
    @Autowired
    private LitemallGrouponRulesService rulesService;

    /**
     * 自动确认订单
     * 租赁订单送达后 凌晨自动确认收货
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void checkOrderUnconfirm() {
        logger.info("系统开启定时任务检查订单是否已经超期自动确认收货");

        // 租赁送达当天自动确认
        List<LitemallOrderItem> leaseList = orderService.queryLeaseUnconfirm();
        for (LitemallOrderItem orderItem : leaseList) {
            // 设置订单自动确认
            orderItem.setOrderStatus(OrderUtil.STATUS_LEASE_AUTO_CONFIRM);
            orderItem.setFinishTime(LocalDateTime.now());
            orderItem.setConfirmTime(LocalDateTime.now());
            if (orderService.updateItemWithOptimisticLocker(orderItem) == 0) {
                logger.info("订单 ID=" + orderItem.getId() + " 数据已经更新，放弃自动确认收货");
            } else {
                logger.info("订单 ID=" + orderItem.getId() + " 已经自动确认收货");
            }
        }

        logger.info("系统结束定时任务检查订单是否已经超期自动确认收货");
    }
}
